// pages/perfect/perfects.js
import WxValidate from '../../utils/WxValidate';
const {
  request
} = require("../../utils/index.js")
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    portrait: '', //头像
    headList: [], //头像路径
    headID: [], //头像ID
    headnum: [], //头像已选个数
    gender: ['女', '男'], //性别
    genderindex: 0, //性别下标
    company: '', //公司
    position: '', //职位
    hobby: '', //爱好
    concerns: '', //关注点
    city: '', //所在城市
    industry:"请选择",  //行业
    birthday: '1980-01-01', //生日
    graduateTime: '2012-09-01', //入校时间
    userdata: [], //用户个人信息
  },

  showSecond() {
    this.second.showSecond()
  },
  chooseItem(e) {
    console.log('用户选择了' + e.detail)
    this.setData({
      industry:e.detail
    })
  },

  //性别
  sexChange: function (e) {
    this.setData({
      genderindex: e.detail.value
    })
    console.log("携带值为：" + this.data.gender[this.data.genderindex])
  },

  //出生日期
  changebirthday(e) {
    this.setData({
      birthday: e.detail.value
    })
    console.log("携带值为：" + this.data.birthday)
  },
  //入校时间
  changegraduat(e) {
    this.setData({
      graduateTime: e.detail.value
    })
    console.log("携带值为：" + this.data.graduateTime)
  },

  //获得用户信息
  async getuserinfo(potions) {
    let that = this
    let token = wx.getStorageSync('token')
    let par = {
      url: "hw/portal/user/self",
      method: "GET",
      data: {
        token: token
      },
      header: {
        'content-type': 'application/json', // 默认值
        'X-Auth-Token': wx.getStorageSync('token')
      },
    }
    let datainfo = await request(par);
    console.log(datainfo)
    if (datainfo.status == 100) {
      if (datainfo.data.graduateTime != undefined) {
        this.setData({
          industry:datainfo.data.industry,  //行业
          graduateTime: datainfo.data.graduateTime, //入校时间
        })
      }
      this.setData({
        userdata: datainfo.data, //用户信息
        portrait: datainfo.data.portrait, //头像
        birthday: datainfo.data.birthday, //出生日期
        genderindex: datainfo.data.gender == "男" ? 1 : 0, //性别
        industryindex: datainfo.data.industryindex //所在行业
      })
      console.log(that.data.portrait)
    }
  },

  // 用户更换头像
  async huanimg() {
    var that = this;
    wx.chooseImage({
      count: 1 - that.data.headnum,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        wx.uploadFile({
          filePath: tempFilePaths[0],
          name: 'file',
          url: 'https://tms.sds.com.cn:8300/hw/upload/files',
          header: {
            'Content-Type': 'multipart/form-data',
          },
          formData: {
            method: 'POST',
            token: wx.getStorageSync('token'),
            sortVal: 1,
            updFileModule: 'user_portrait',
            updFileType: 'pic',
          },
          success(res2) {
            var res = JSON.parse(res2.data)
            if (res.status == 100) {
              var headList = that.data.headList.concat(tempFilePaths[0]); //获取到上传的头像
              that.data.headID.push(res.data.updId)
              that.setData({
                portrait: headList,
                headnum: headList.length
              })
              console.log(headList)
              console.log(that.data.portrait)
            }
          }
        })
      }
    })
  },
  backht: function () {
    wx.navigateBack({
      delta: 1,
    })
  },
  // 非空验证
  initValidate() {
    const rules = {
      school: {
        required: true
      },
      company: {
        required: true
      },
      position: {
        required: true
      },
      city: {
        required: true
      },
    }
    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      school: {
        required: '请输入所在大学',
      },
      company: {
        required: '请输入公司名称',
      },
      position: {
        required: '请输入职位',
      },
      city: {
        required: '请输入所在城市',
      },
    };
    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages)
  },

  //获得微信登录用户头像
  getUserProfile: function (e) {
    var that = this;
    if (that.data.portrait == "https://tms.sds.com.cn:8300/pic/icon/def.png") {
      wx.getUserProfile({
        desc: '展示用户头像',
        success: (res) => {
          that.setData({
            portrait: res.userInfo.avatarUrl //头像
          })
        },
        fail() {
          console.log("error");
        }
      })
    // let par = {
    //   url: 'hw/upload/files',
    //   header: {
    //     'Content-Type': 'multipart/form-data',
    //     'token':wx.getStorageSync('token'),
    //     "file": that.data.portrait,
    //     "sortVal": "1",
    //     "updFileModule": "user_portrait",
    //     "updFileType": "pic",
    //   },
    //   method: "POST"
    // }
    // let datainfo = await request(par);
    // console.log(datainfo)
    // if (datainfo.status == 100) {
    //   console.log(请求成功)
    // }else{

    // }
    }
  },

  /***4-3(表单提交校验)*/
  async submitForm(e) {
    let that = this
    console.log(that.data.graduateTime)
    const params = e.detail.value
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    }
    this.getUserProfile();
    // 验证通过以后->
    if (that.data.portrait != "https://tms.sds.com.cn:8300/pic/icon/def.png") {
      let parm = {
        url: 'hw/portal/user/upd_user_info?token=' + wx.getStorageSync('token'),
        data: {
          portrait: this.data.portrait, //头像
          gender: this.data.gender[this.data.genderindex], //性别
          companyInfo: params.company, //公司
          focus: params.concerns, //关注点
          hobby: params.hobby, //爱好
          positionInfo: params.position, //职位
          cityInfo: params.city, //所在城市
          birthday: this.data.birthday, //出生日期
          userEmail: params.userEmail, //邮箱号
          remarks: params.remarks, //我的标签
          school: params.school, //所在大学
          graduateTime: this.data.graduateTime, //入校时间
          industry: this.data.industry, //所在行业
        },
        method: 'POST',
        header: {
          'content-type': 'application/json', // 默认值
        },
      }
      let data = await request(parm);
      if (data.status == 100) {
        wx.showModal({
          title: '保存成功！',
          confirmText: "确认",
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.navigateBack({
                delta: 1,
              })
            }
          }
        })
      }
    }
  },
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getuserinfo();
    this.initValidate();
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.second = this.selectComponent("#second")
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})